package oh.june.calleridentifier;

import oh.june.calleridentifier.module.DataRow;
import oh.june.calleridentifier.module.DataRowBean;
import oh.june.calleridentifier.module.DataTable;
import oh.june.calleridentifier.module.DateUtil;
import oh.june.calleridentifier.module.DbHelper;
import oh.june.calleridentifier.module.ListCustomAdapter;
import oh.june.calleridentifier.module.RoundButton;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MemoListActivity extends Activity implements OnClickListener{

	private int BACK_MODE = 0;
	private static final int BACK_MODE_NORMAL 	= 0;
	private static final int BACK_MODE_DEL 		= 1;	
	private ListCustomAdapter mAdapter;
	
	private boolean mDoubleClick = false;
	
	private RoundButton mBtnDel;
	private Button mBtnNew;
	private ToggleButton mBtnDelList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);
		
		TextView tvTitle = (TextView)findViewById(R.id.title);
		tvTitle.setTypeface(Typeface.DEFAULT_BOLD);
		tvTitle.setTextColor(Color.rgb(240, 240, 240));
		
		EditText edtSearch = (EditText)findViewById(R.id.input_edit);
		edtSearch.setTypeface(Typeface.DEFAULT);
		edtSearch.addTextChangedListener(mTextWatcher());

		mBtnDel = (RoundButton)findViewById(R.id.btn_delete);
		
		final ListView list = (ListView)findViewById(R.id.listview);
		mAdapter = new ListCustomAdapter(this, new DataTable());
		list.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		mAdapter.setOnBtnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				int id = v.getId();
				
				int position = (Integer) v.getTag();
				DataRow row = mAdapter.getItem(position);
				
				switch(id){
				case R.id.btn_toNext:
					call(row.getString("NUMBER",  ""));
					break;
				case R.id.list_base:
					showCallDialog(row);
					break;
				}
			}
		});
		list.setLongClickable(true);

		mBtnNew = (Button)findViewById(R.id.btn_new);
		mBtnDelList = (ToggleButton)findViewById(R.id.btn_list);
		mBtnDelList.setChecked(false);
		
		mBtnNew.setOnClickListener(this);
		mBtnDelList.setOnClickListener(this);
		mBtnDel.setOnClickListener(this);
		
	}

	private TextWatcher mTextWatcher() {
		TextWatcher watcher = new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			
			@Override
			public void afterTextChanged(Editable s) {
				mAdapter.clear();
				mAdapter.addAll(getListItems(s.toString()));
				mAdapter.notifyDataSetChanged();
			}
		};
		return watcher;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		resetMode();
		
	}

	protected void resetMode() {
		
		mDoubleClick = false;
		
		BACK_MODE = BACK_MODE_NORMAL;

		mAdapter.clear();
		mAdapter.addAll(getListItems());
		mAdapter.notifyDataSetChanged();
		mAdapter.setCheckboxShow(false);
		
		mBtnDelList.setChecked(false);
		mBtnDel.setVisibility(View.GONE);
		mBtnNew.setVisibility(View.VISIBLE);
		
	}

	protected void showCallDialog(final DataRow row) {
		try{
			//		A.NUMBER, A.NAME, B.MEMO, B.INS_DT
			StringBuilder strBuilder = new StringBuilder();
			strBuilder.append("Number : " + row.getString("NUMBER", ""));
			strBuilder.append("\r\n");
			strBuilder.append("Name   : " + row.getString("NAME", ""));
			strBuilder.append("\r\n");
			strBuilder.append("Memo   : " + row.getString("MEMO", ""));
			strBuilder.append("\r\n");
			strBuilder.append("Time   : " + DateUtil.toPatternedDate("yyyy.MM.dd HH:mm:ss", "yyyyMMddHHmmss", row.getString("INS_DT", "")));
			//strBuilder.append("Time   : " + row.getString("INS_DT", ""));
			String messageStr = strBuilder.toString();

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Caller information");
			builder.setMessage(messageStr);
			builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					call(row.getString("NUMBER", ""));
				}
			});

			builder.setNeutralButton("Modify", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent i = new Intent(MemoListActivity.this, MemoActivity.class);
					i.putExtra("MODIFY_DATA", new DataRowBean(row));
					startActivityForResult(i, 1001);
				}
			});

			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builder.create().show();	
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	protected void call(String string) {
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:" + string));
		this.startActivity(callIntent);
	}
	
	private DataTable getListItems(){
		return getListItems("");
	}

	private DataTable getListItems(String keyword) {
		DbHelper helper = DbHelper.getInstance(this);
		DataTable list = helper.selectList(keyword);
		return list;
	}

	@Override
	public void onBackPressed() {
		if(BACK_MODE == BACK_MODE_DEL){
			resetMode();
		}else{
			super.onBackPressed();	
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		resetMode();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id){
		case R.id.btn_new:
			
			Intent i = new Intent(MemoListActivity.this, MemoActivity.class);
			startActivity(i);
			break;
			
		case R.id.btn_list:
			if(mBtnDelList.isChecked()){
				mBtnNew.setVisibility(View.GONE);
				
				BACK_MODE = BACK_MODE_DEL;

				Vibrator vi = (Vibrator) MemoListActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
				vi.vibrate(100);
				
				mBtnDel.setVisibility(View.VISIBLE);
				mAdapter.setCheckboxShow(true);
			}else{
				resetMode();
			}
			break;
			
		case R.id.btn_delete:
			deleteCheckedItems();
			break;
		}
	}
	
	private void deleteCheckedItems(){
		
		if(mDoubleClick)
			return;
		
		mDoubleClick = true;
		
		DbHelper helper = DbHelper.getInstance(MemoListActivity.this);
		DataTable delList = mAdapter.getCheckedItems();
		for(DataRow row : delList){
			String number = row.getString("NUMBER", "");
			String insDt = row.getString("INS_DT", "");
			helper.deleteMemo(number, insDt);
		}
		resetMode();
		
	}


}
